﻿using Domain;
using Domain.Model;
using Domain.Model.Enums;
using Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Web.Controllers
{
    public class UserController : LoginedController
    {
        public ActionResult Index()
        {
            return View();
        }
        //待激活会员
        public ActionResult Activate()
        {            
            return View();
        }
        public ActionResult ActivatePage(int pageIndex, int pageSize, string keyword)
        {
            var where = Where.True<User>();
            where = where.And(i => i.VerifyState == VerifyState.审核中);
            if (keyword != null)
                where = where.And(i => i.Account.Contains(keyword) || i.Name.Contains(keyword));
            var list = DbContext.User.Where(where).OrderByDescending(i => i.CreateTime).ToPage(pageIndex, pageSize);
            return this.PageResult(list.TotalCount, this.ViewHtml(list));
        }

        public ActionResult UserEdit(Guid id)
        {
            ViewData["operate"] = "Edit";
            var item = new List<SelectListItem>();
            item.Add(new SelectListItem() { Text = "男", Value = "1" });
            item.Add(new SelectListItem() { Text = "女", Value = "0" });
            ViewData["Gender"] = item;
            ViewBag.Link = "/user/userList";

            User model = DbContext.User.Find(id);
            return View(model);
        }
        [HttpPost]
        public ActionResult UserEdit(User model)
        {
            if (ModelState.IsValid == false)
            {
                return Json(new { state = false, value = ModelState.FirstModelError().ErrorMessage });
            }

            if (DbContext.User.Any(i => i.ID == model.ID))
            {
                DbContext.User.Update(this.DbContext, model);
            }
            else
            {
                model.RoleId = Global.Roles.CustomerID;

                DbContext.User.Add(model);
                DbContext.SaveChanges();

                //if (model.Referrer == null)
                //    model.Referrer = LoginUser.Account;
                //var referrerId = DbContext.User.Where(i => i.Account == model.Referrer).Select(i => i.ID).FirstOrDefault();
                //var recommend = new Recommend() { MyId = model.ID, RecommenderId = referrerId };
                //DbContext.Recommend.Add(recommend);
            }

            DbContext.SaveChanges();
            return Json(new { state = true, value = string.Empty });
        }
        //用户列表
        public ActionResult UserList()
        {
            return View();
        }
        public ActionResult UserPage(int pageIndex, int pageSize, string keyword)
        {
            var where = Where.True<User>();
            where = where.And(i => i.VerifyState == VerifyState.通过);
            if (keyword != null)
                where = where.And(i => i.Account.Contains(keyword) || i.Name.Contains(keyword));
            var list = DbContext.User.Where(where).OrderByDescending(i => i.CreateTime).ToPage(pageIndex, pageSize);
            return this.PageResult(list.TotalCount, this.ViewHtml(list));
        }

        //激活
        public ActionResult ActivateMenber(Guid id)
        {
            var model = DbContext.User.Find(id);
            model.VerifyState = VerifyState.通过;
            DbContext.User.Update(this.DbContext, model);

            try
            {
                //历史
                var userHistory = new UserHistory()
                {
                    Account = model.Account,
                    NickName = model.NickName,
                    Level = model.Level,
                    NvestmentAmount = model.NvestmentAmount,
                    CreateTime = model.CreateTime,
                    ActivateType = "管理员",
                    ActivateNoName = model.Account + "/" + model.NickName,
                    State = model.VerifyState,
                    ActivateTime = DateTime.Now,
                    ConfirmNickName = model.NickName,
                    ConfirmNo = model.Account,
                    HistoryType = HistoryType.会员激活记录,
                    IsValid = true
                };
                DbContext.UserHistory.Add(userHistory);
                DbContext.SaveChanges();
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                throw ex;
            }

            return Json(new { state = true, value = "激活成功！" });
        }

        //激活历史
        public ActionResult UserActivateHistroy()
        {
            return View();
        }
        public ActionResult UserActivateHistroyPage(int pageIndex, int pageSize, string keyword)
        {
            var list = GetUserHistoryByTpye(pageIndex, pageSize, keyword, HistoryType.会员激活记录);
            return this.PageResult(list.TotalCount, this.ViewHtml(list));
        }
        //根据类型获取记录
        public PageInfo<UserHistory> GetUserHistoryByTpye(int pageIndex, int pageSize, string keyword, HistoryType HistoryType)
        {
            var where = Where.True<UserHistory>();
            keyword = keyword != null ? keyword : string.Empty;
            where = where.And(i => i.HistoryType == HistoryType)
                .And(i => i.Account.Contains(keyword) || i.NickName.Contains(keyword));

            var list = DbContext.UserHistory.Where(where)
                .OrderByDescending(i => i.ActivateTime).ToPage(pageIndex, pageSize);
            return list;
        }
        //注册
        public ActionResult Register()
        {
            var item = new List<SelectListItem>();
            item.Add(new SelectListItem() { Text = "男", Value = "1" });
            item.Add(new SelectListItem() { Text = "女", Value = "0" });
            ViewData["Gender"] = item;

            //ViewBag.Link = "/user/userlist";
            User model = new User()
            {
                Account = DbContext.Database.NewCustormerNo()
            };
            return View("UserEdit", model);
        }

        //后台修改记录
        public ActionResult LevelsHistory()
        {
            return View();
        }
        public ActionResult LevelsHistoryPage(int pageIndex, int pageSize, string keyword)
        {
            var list = GetUserHistoryByTpye(pageIndex, pageSize, keyword, HistoryType.级别修改记录);
            return this.PageResult(list.TotalCount, this.ViewHtml(list));
        }

        //后台级别申请
        public ActionResult LevelsApply()
        {
            return View();
        }
        public ActionResult LevelsApplyPage(int pageIndex, int pageSize, string keyword)
        {
            var list = GetUserHistoryByTpye(pageIndex, pageSize, keyword, HistoryType.级别申请记录);
            return this.PageResult(list.TotalCount, this.ViewHtml(list));
        }

        [HttpPost]
        public ActionResult CheckReferrer(string referrer)
        {
            var exists = this.DbContext.User.Any(item => item.Account == referrer);
            return Json(new { state = exists, message = "推荐人不存在.." });
        }
    }
}
